﻿using System;
using System.Linq;
using System.Xml.Linq;
using MimosaProductsEF.Model;

namespace XMLReaderAndWriter
{
    public class XMLReportCreator
    {
        private static XElement salesReport = new XElement("sales");

        public static void CreateReport()
        {
            using (var db = new MimosaProductsEntitiesEF())
            {
                var vendors = (from s in db.Sales
                               join p in db.Products on s.ProductId equals p.ProductId
                               join v in db.Vendors on p.VendorId equals v.VendorId
                               select v).Distinct();

                foreach (var vendor in vendors)
                {
                    salesReport.Add(CreateSaleElement(vendor.VendorId, vendor.VendorName));
                }
            }

            salesReport.Save("../../Sales-by-Vendors-report.xml");
        }

        private static XElement CreateSaleElement(int vendorId, string vendorName)
        {
            MimosaProductsEntitiesEF db = new MimosaProductsEntitiesEF();

            using (db)
            {
                var entries = from s in db.Sales
                              join p in db.Products on s.ProductId equals p.ProductId
                              join v in db.Vendors on p.VendorId equals v.VendorId
                              where v.VendorId == vendorId
                              group s by s.Date into y
                              select new
                              {
                                  Date = y.Key,
                                  Sum = y.Sum(x => x.Sum)
                              };

                XElement sale = new XElement("sale");
                foreach (var entry in entries)
                {
                    sale.SetAttributeValue("vendor", vendorName);

                    sale.Add(new XElement("summary", new XAttribute("date", entry.Date), new XAttribute("total-sum", entry.Sum)));
                }

                return sale;
            }
        }
    }
}
